<?php

$dbConfig = simplexml_load_file('src/dao/dbconfig.xml'); 

backup_tables($dbConfig->host, $dbConfig->dbname, $dbConfig->password, $dbConfig->dbname);

$files  = array();
$dir    = opendir('backups/'); 
while(($f = readdir($dir)) !== FALSE){
    if(!strcmp($f, '.') || !strcmp($f, '..') || !strcmp($f, '.htaccess')) continue;
    $files[] = 'backups/'.$f;
}
closedir($dir);

if(count($files) >= 8) {
    usort($files, 'cmp');
    $size = count($files);
    while($size > 6){
        $tag = array_pop($files);
        unlink($tag);
        $size--;
    }
}

function cmp($f1, $f2){
    return filemtime($f2) - filemtime($f1);
}

/* backup the db OR just a table */
function backup_tables($host,$user,$pass,$name,$tables = '*')
{
	
    $link = mysql_connect($host,$user,$pass);
    mysql_select_db($name,$link);

    //get all of the tables
    if($tables == '*')
    {
        $tables = array();
        $result = mysql_query('SHOW TABLES');
        while($row = mysql_fetch_row($result))
        {
            $tables[] = $row[0];
        }
    } else {
        $tables = is_array($tables) ? $tables : explode(',',$tables);
    }
    
    $return = "";
    
    //cycle through
    foreach($tables as $table)
    {
        $result = mysql_query('SELECT * FROM '.$table);
        $num_fields = mysql_num_fields($result);

        /**
         * Somente os dados vão ser exportados.
         * Para exportar as estruturas, descomentar as linhas abaixo.
         */
        
        $return.= 'DROP TABLE '.$table.';';
        $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
        $return.= "\n\n".$row2[1].";\n\n";

        for ($i = 0; $i < $num_fields; $i++) 
        {
            while($row = mysql_fetch_row($result)) {
                $return.= 'INSERT INTO '.$table.' VALUES(';
                for($j=0; $j<$num_fields; $j++) 
                {
                    if($row[$j] === NULL){
                        $return .= 'NULL';
                    } else {
                        $row[$j] = addslashes($row[$j]);
                        $row[$j] = ereg_replace("\n","\\n",$row[$j]);
                        if (isset($row[$j])){$return.= '"'.$row[$j].'"';} else {$return.= '""';}
                    }
                    if ($j<($num_fields-1)) { $return.= ','; }
                }
                $return.= ");\n";
            }
        }
        $return.="\n\n\n";
    }
    
    $dateName   = date('Y-m-d');
    $sufix      = strcmp(date('a'), 'am') ? '_NOITE.sql' : '_DIA.sql';

    //save file
    $handle = fopen('backups/backup_'.$dateName.$sufix, 'w+');
    fwrite($handle, $return);
    fclose($handle);
}
?>
